package com.wanshi.dao;

import com.wanshi.entity.User;
import com.wanshi.utils.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;

import java.sql.Connection;
import java.sql.SQLException;

public class UserDao {

    //根据用户名查询用户是否存在
    public User findUserByName(String name){
        String sql = "select * from user where username = ?";
        QueryRunner runner = new QueryRunner(JDBCUtil.getSource());
        try {
            return runner.query(sql, new BeanHandler<>(User.class),name);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    //添加用户
    public void addUser(Connection conn, User user) throws SQLException {
        String sql = "insert into user values(null,?,?,?,?,?,?,null,?)";
        QueryRunner runner = new QueryRunner();
        runner.update(conn,sql,user.getUsername(),user.getPassword(),user.getNickname(),
                user.getEmail(),user.getState(),user.getStatecode(),user.getRole_id());
    }

    //根据激活码查询用户是否存在
    public User findUserByCode(String code){
        String sql = "select * from user where statecode = ?";
        QueryRunner runner = new QueryRunner(JDBCUtil.getSource());
        try {
            return runner.query(sql, new BeanHandler<User>(User.class),code);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public void deleteUserByCode(String statecode) {
        String sql = "delete from user where statecode = ?";
        QueryRunner runner = new QueryRunner(JDBCUtil.getSource());
        try {
            runner.update(sql,statecode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public void updateUserByCode(String statecode) {
        String sql = "update user set state = 1 where statecode = ?";
        QueryRunner runner = new QueryRunner(JDBCUtil.getSource());
        try {
            runner.update(sql,statecode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public User findUserByNameAndPsd(String username, String password) {
        String sql = "select * from user where username = ? and password = ?";
        QueryRunner runner = new QueryRunner(JDBCUtil.getSource());
        try {
            return runner.query(sql, new BeanHandler<User>(User.class),username,password);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }
}
